import { getPageListData } from '@/service/system/system'
import { IRootState } from '@/store/types'
import { Module } from 'vuex'
import { ISystemState } from './types'

const systemStore: Module<ISystemState, IRootState> = {
  namespaced: true,
  state() {
    return {
      userList: [],
      userCount: 0,
      roleList: [],
      roleCount: 0
    }
  },
  getters: {
    pageListData(state) {
      return (pageName: string) => {
        switch (pageName) {
          case 'user':
            return state.userList
            break
          case 'role':
            return state.roleList
            break
        }
      }
    }
  },
  actions: {
    async getPageListAction({ commit }, payload: any) {
      // 1. 对页面发送请求
      // const { data: res } = await getPageListData(payload.url, payload.userInfo)
      // commit('changeUserList', res.list)
      // commit('changeUserCount', res.totalCount)
      const pageName = payload.pageName
      const PageNames = {
        user: '/users/list',
        role: '/role/list'
      }
      // 处理首字母大写问题
      const N = pageName.charAt(0).toUpperCase()
      const newPageName = pageName.slice(1, pageName.length)
      // 1.判断pageName为哪个路由
      let pageUrl = ''
      switch (pageName) {
        case 'user':
          pageUrl = PageNames.user
          break
        case 'role':
          pageUrl = PageNames.role
          break
      }

      // 2.请求
      // console.log(pageUrl, payload)
      const { data: res } = await getPageListData(pageUrl, payload.queryInfo)

      // 3.提交更改
      commit(`change${N}${newPageName}List`, res.list)
      commit(`change${N}${newPageName}Count`, res.totalCount)
    }
  },
  mutations: {
    // 改变state中的userList的mutation
    changeUserList(state, payload: Object[]) {
      state.userList = payload
    },
    // 改变state中的userCount的mutation
    changeUserCount(state, payload: number) {
      state.userCount = payload
    },
    // 改变state得roleList得mutation
    changeRoleList(state, payload: Object[]) {
      state.roleList = payload
    },
    // 改变state得roleCount的mutation
    changeRoleCount(state, payload: number) {
      state.roleCount = payload
    }
  }
}
export default systemStore
